<?php
namespace app\admin\validate;

use think\Validate;

class SiteValidate extends Validate
{
    protected $rule = [
        'name'   => 'require',
        'domain' => 'checkDomain',
    ];

    protected $message = [
        'name.require'   => '站点名称不能为空',
        // 'domain.require' => '站点域名不能为空',
    ];

    protected function checkDomain($value, $rule, $data){

        $where = [
            'domain' => $value,
        ];
        
        if( !empty($data['site_id']) ){
            $where['site_id'] = ['neq',$data['site_id']];
        }

        if( !empty($value) ){
            $chars  = '/[\w-_\.]+\.[\w-_\.]+/i';
            if ( !preg_match($chars, $value) ) {
                return '站点域名不规范';
            }
            // elseif ( array_key_exists($value, $domain) ) {
            //     return '站点域名 '.$value.' 已经存在';
            // }
            elseif ( db('site')->where($where)->count() ) {
                return '站点域名 '.$value.' 已经被使用了';
            }
        }

        return true;
    }
}
